import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes } from '@/router/routes'

//引入api
import { reqLogin,  reqLogout, reqUserInfo } from '@/api/acl/login';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

  actions: {
    //登录
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ password, username })
        this.token = result.token;
        setToken(result.token);
        return 'ok';
      } catch (error) {
        return Promise.reject('失败');
      }
    },

    //获取用户信息
    async getInfo() {
      try {
        let result = await reqUserInfo()
        this.name = result.name;
        this.avatar = result.avatar;
        this.menuRoutes = staticRoutes;
        return 'ok';
      } catch (error) {
        return Promise.reject('失败');
      }
    },

    //退出登录
    async reset() {
      try {
        await reqLogout()
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.name = ''
        this.avatar = ''
        return 'ok';
      } catch (error) {
        return Promise.reject('失败');
      }
    },
  },
});
